package com.wanxi.servlet;

import com.alibaba.fastjson2.JSONObject;
import com.wanxi.dto.ResultDTO;
import com.wanxi.service.UserService;
import com.wanxi.service.impl.UserServiceImpl;
import com.wanxi.vo.UserVO;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        1.乱码处理
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
//        2.得到前端数据
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String code = req.getParameter("code");
        String sessionCode = (String) req.getSession().getAttribute("vCode");
        //        3.封装到model
//        数据库的表和Java里面的model一致
//        以后Java的model和数据库一致
//        前端的数据封装到vo里面去view Object
        UserVO userVO = UserVO.builder()
                .username(username)
                .password(password)
                .code(code)
                .sessionCode(sessionCode)
                .build();
//        4.将对象传递到服务逻辑层
//        为什么要用多态？父类，接口或者抽象 目的：为了扩展
        UserService userService = new UserServiceImpl();
//        5.得到服务逻辑层的返回值
        ResultDTO obj = userService.login(userVO);
        if (obj.getMsg().equals("success")) {
            req.getSession().setAttribute("username", username);
        }

//        6.将结果返回给web前端
        resp.getWriter().println(JSONObject.toJSONString(obj));
    }
}
